package pl.org.lutra.planner.model.input;

import java.awt.Toolkit;
import java.util.Observer;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;

import pl.org.lutra.planner.model.ModelObserverEvent;

public class FloatDocumentFilter extends DocumentFilter {

	private ChangedObservable observable = new ChangedObservable();

	@Override
	public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs)
			throws BadLocationException {
		Document document = fb.getDocument();

		String newText = document.getText(0, document.getLength()) + text;
		try {
			Float.parseFloat(newText);
			super.replace(fb, offset, length, text, attrs);

			observable.notifyObservers(ModelObserverEvent.INPUT_CHANGED);
		} catch (NumberFormatException exception) {
			Toolkit.getDefaultToolkit().beep();
		}
	}

	@Override
	public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
		super.remove(fb, offset, length);

		observable.notifyObservers(ModelObserverEvent.INPUT_CHANGED);
	}

	@Override
	public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
		super.insertString(fb, offset, string, attr);

		observable.notifyObservers(ModelObserverEvent.INPUT_CHANGED);
	}

	public void addObserver(Observer observer) {
		observable.addObserver(observer);
	}
}
